//
//  htvloadcity.m
//  MaiYaApp
//
//  Created by zhangwq on 15/10/21.
//  Copyright © 2015年 HT. All rights reserved.
//

#import "htvloadcity.h"
#import "HTSysParam.h"
#import "HTFrameNet.h"
#import "pinyin.h"
#import "ChineseString.h"
#import "HTFrameAlert.h"



static NSString *SectionsTableIdentifier=@"cellname";

@interface htvloadcity (){
    NSMutableArray *cityArray;
    NSMutableArray *queryArray;
    NSMutableArray *keys;
    NSMutableDictionary *cities;
    NSMutableArray *hotCityArray;
    NSMutableArray *sortedArrForArrays;
    NSMutableArray *cityArray2;
    CGFloat width;
    UIView *uv;
    CGFloat hotHeight;
    int rowcount;
}

@end

@implementation htvloadcity

- (void)viewDidLoad {
    [super viewDidLoad];
    
    cityArray=[NSMutableArray array];
    queryArray=[NSMutableArray array];
    keys=[NSMutableArray array];
    cities=[[NSMutableDictionary alloc]init];
    sortedArrForArrays=[NSMutableArray array];
    cityArray2=[NSMutableArray array];
    
    CGRect rect = [[UIScreen mainScreen] bounds];
    CGSize size = rect.size;
    width = size.width;
    
    uv=[[UIView alloc]init];
    
    hotHeight=40;
    rowcount=1;
    
    self.title=[[NSString alloc]initWithFormat:@"当前城市-%@",[HTSysParam city] ];
    

    
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:194.0/255 green:7.0/255 blue:30.0/255 alpha:1.0f];
    
    self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:
     
     @{NSFontAttributeName:[UIFont systemFontOfSize:15],
       
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    
    self.tableView.sectionIndexColor = [UIColor redColor];
    
    
    
    [self refreshListData];
    
    
}


-(void)getKeys{
    
    
    cities=[[NSMutableDictionary alloc]init];
    NSString * pinyin=nil;
    NSMutableArray *arr=nil;
    for (int i=0;i<[cityArray count];i++) {
        NSDictionary *dict=[cityArray objectAtIndex:i];
        NSString *city=[dict objectForKey:@"city"];
        
        for (int i = 0; i < [city length]; i++)
        {
            if(i==0){
                char c=pinyinFirstLetter([city characterAtIndex:i]);
                pinyin=[[NSString alloc]initWithFormat:@"%c",c ];
            }
        }
        
        //如果包含key
        if([[cities allKeys]containsObject:pinyin]){
            arr=[cities objectForKey:pinyin];
            [arr addObject:city];
            [cities setObject:arr forKey:pinyin];
        }else{
            arr= [[NSMutableArray alloc]initWithObjects:city, nil];
            [cities setObject:arr forKey:pinyin];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



//刷新数据
-(void)refreshListData
{
    NSString *serverUrl=[[NSString alloc]initWithFormat:@"%@\/%@\/",[HTSysParam erpServer],[HTSysParam erpVirDir]];
    HTFrameNet *htnet=[[HTFrameNet alloc] initWithServerUrl:serverUrl];
    
    NSDictionary *dict = @{};
    [htnet hmNetWCFmethodName:@"city/getList" andDic:dict complete:^(NSString *backstr)
     {
         NSDictionary *rootDict=[HTFrameNet hmConvertDictFromJsonStr:backstr];
         NSDictionary *body=[rootDict objectForKey:@"body"];
         if(body!=nil){
             
             cityArray=[body objectForKey:@"dataList"];
             
             [keys addObjectsFromArray:[[cities allKeys] sortedArrayUsingSelector:@selector(compare:)]];
             
             cityArray2=[NSMutableArray array];
             hotCityArray=[NSMutableArray array];
             int hotIndex=0;
             for (int i=0;i<[cityArray count];i++) {
                 NSDictionary *dict=[cityArray objectAtIndex:i];
                 NSString *city=[dict objectForKey:@"city"];
                 [cityArray2 insertObject:city atIndex:i];
                 int hotFlag=[[dict objectForKey:@"hotFlag"]intValue];
                 if(hotFlag==1&&![city isEqualToString:@""]){
                     [hotCityArray insertObject:[dict objectForKey:@"city"] atIndex:hotIndex];
                     hotIndex=hotIndex+1;
                 }
             }
             
             if([hotCityArray count]%3==0){
                 rowcount=[hotCityArray count]%3;
             }
             else{
                 rowcount=[hotCityArray count]%3+1;
             }
             
             hotHeight=30*rowcount+5*(rowcount+1);
             
             
             sortedArrForArrays = [ self getChineseStringArr : cityArray2 ];
             
             //添加热门城市
             NSString *strHot = @"热";
             [keys insertObject:strHot atIndex:0];
             NSDictionary *hotDict=@{@"chineseString":@"AA"};
             [sortedArrForArrays insertObject:hotDict atIndex:0];
             

             
             [self.tableView reloadData];
         }
         
    
         
         
     }];
    
}


- ( NSMutableArray *)getChineseStringArr:( NSMutableArray *)arrToSort

{
    
    // 创建一个临时的变动数组
    NSMutableArray *chineseStringsArray = [ NSMutableArray array ];
    for ( int i = 0 ; i < [arrToSort count ]; i++)
    {
        // 创建一个临时的数据模型对象
        
        ChineseString *chineseString=[[ ChineseString alloc ] init ];
        chineseString.string =[ NSString stringWithString :[arrToSort objectAtIndex :i]];
        
        if (chineseString. string == nil )
        {
            chineseString. string = @"" ;
        }
        
        if (![chineseString. string isEqualToString : @"" ])
        {
            //join( 链接 ) the pinYin (letter 字母 )  链接到首字母
            NSString *pinYinResult = [ NSString string ];
            // 按照数据模型中 row 的个数循环
            for ( int j = 0 ;j < chineseString. string . length ; j++)
            {
                NSString *singlePinyinLetter = [[ NSString stringWithFormat : @"%c" ,
                                                 
                                                 pinyinFirstLetter ([chineseString. string characterAtIndex :j])] uppercaseString ];
                pinYinResult = [pinYinResult stringByAppendingString :singlePinyinLetter];
                
            }
            
            chineseString. pinYin = pinYinResult;
            
        } else {
            
            chineseString. pinYin = @"" ;
            
        }
        
        [chineseStringsArray addObject :chineseString];
        
    }
    //sort( 排序 ) the ChineseStringArr by pinYin( 首字母 )
    
    NSArray *sortDescriptors = [ NSArray arrayWithObject :[ NSSortDescriptor sortDescriptorWithKey : @"pinYin" ascending : YES ]];
    [chineseStringsArray sortUsingDescriptors :sortDescriptors];
    NSMutableArray *arrayForArrays = [ NSMutableArray array ];
    BOOL checkValueAtIndex= NO ;  //flag to check
    NSMutableArray *TempArrForGrouping = nil ;
    for ( int index = 0 ; index < [chineseStringsArray count ]; index++)
    {
        ChineseString *chineseStr = ( ChineseString *)[chineseStringsArray objectAtIndex :index];
        
        NSMutableString *strchar= [ NSMutableString stringWithString :chineseStr. pinYin ];
        
        NSString *sr= [strchar substringToIndex : 1 ];
        
        
        
        //sr containing here the first character of each string  ( 这里包含的每个字符串的第一个字符 )
        
        
        //here I'm checking whether the character already in the selection header keys or not  ( 检查字符是否已经选择头键 )
        if (![ keys containsObject :[sr uppercaseString ]])
        {
            [ keys addObject :[sr uppercaseString ]];
            TempArrForGrouping = [[ NSMutableArray alloc ] initWithObjects : nil ]  ;
            checkValueAtIndex = NO ;
        }
        if ([ keys containsObject :[sr uppercaseString ]])
            
        {
            [TempArrForGrouping addObject :[chineseStringsArray objectAtIndex :index]];
            if (checkValueAtIndex == NO )
            {
                [arrayForArrays addObject :TempArrForGrouping];
                checkValueAtIndex = YES ;
            }
        }
        
    }
    
    return arrayForArrays;
    
}







-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([indexPath section]==0){
        return hotHeight;
    }
    else{
        return 50;
    }
}


- ( NSInteger )tableView:( UITableView *)tableView numberOfRowsInSection:( NSInteger )section

{
    
    return   [[ sortedArrForArrays objectAtIndex :section] count ];
    
}


- ( NSInteger )numberOfSectionsInTableView:( UITableView *)tableView

{
    
    return [ sortedArrForArrays count ];
    
}


// 为 section 添加标题

- ( NSString *)tableView:( UITableView *)tableView titleForHeaderInSection:( NSInteger )section

{
    if([[ keys objectAtIndex :section] isEqualToString:@"热"])
    {
        return @"热门城市";
    }
    else{
        return [ keys objectAtIndex :section];
    }
    
    
}



- ( NSArray *)sectionIndexTitlesForTableView:( UITableView *)tableView

{
    
    return keys ;
    
}


// 创建 tableView 的 cell

- ( UITableViewCell *)tableView:( UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath

{
    
    NSString *cellId = @"cellname" ;
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier :cellId];
    
    if (cell == nil ) {
        
        
        
        cell = [[ UITableViewCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier :cellId] ;
        
    }
    
    if([indexPath section]==0)
    {
        
        uv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width-30, hotHeight)];
        NSString *city=@"";
        for(int i=0;i<rowcount;i++){
            
            CGFloat cgwidth=(width-60)/3;
            
            if([hotCityArray count]>i*3)
            {
              city=[hotCityArray objectAtIndex:i*3];
              UIButton *btn1=[[UIButton alloc]initWithFrame:CGRectMake(15, 5*(i+1)+30*(i), cgwidth, 30)];
              [btn1 setTitle:city forState:UIControlStateNormal];
              [btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
              [btn1 setFont: [UIFont systemFontOfSize: 12.0]];
              btn1.layer.borderColor=[UIColor blackColor].CGColor;
              [btn1.layer setBorderWidth:0.5];
              [btn1 addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchDown];
              [uv addSubview:btn1];
            }
            
            if([hotCityArray count]>i*3+1)
            {
              city=[hotCityArray objectAtIndex:i*3+1];
              UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake(30+cgwidth, 5*(i+1)+30*(i), cgwidth, 30)];
              [btn2 setTitle:city forState:UIControlStateNormal];
              [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
              [btn2 setFont: [UIFont systemFontOfSize: 12.0]];
              btn2.layer.borderColor=[UIColor blackColor].CGColor;
              [btn2.layer setBorderWidth:0.5];
              [btn2 addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchDown];
              [uv addSubview:btn2];
            }
            
            if([hotCityArray count]>i*3+2)
            {
              city=[hotCityArray objectAtIndex:i*3+2];
              UIButton *btn3=[[UIButton alloc]initWithFrame:CGRectMake(45+cgwidth*2, 5*(i+1)+30*(i), cgwidth, 30)];
              [btn3 setTitle:city forState:UIControlStateNormal];
              [btn3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
              [btn3 setFont: [UIFont systemFontOfSize: 12.0]];
              btn3.layer.borderColor=[UIColor blackColor].CGColor;
              [btn3.layer setBorderWidth:0.5];
              [btn3 addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchDown];
              [uv addSubview:btn3];
            }

            
        }
        
    }
    else{
        
        if ([ sortedArrForArrays count ] > indexPath. section-1)
            
        {
            
            NSArray *arr = [ sortedArrForArrays objectAtIndex :indexPath. section];
            
            if ([arr count ] > indexPath. row)
                
            {
                
                ChineseString *str = ( ChineseString *) [arr objectAtIndex :indexPath. row ];
                uv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width-30, 30)];
                
                UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(15, 5, width, 20)];
                [btn setTitle:str. string forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [btn setFont: [UIFont systemFontOfSize: 12.0]];
                btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;
                [btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchDown];
                [uv addSubview:btn];
                
            }
            
            else {
                
                NSLog ( @"arr out of range" );
                
            }
            
        }
        
        else
            
        {
            
            NSLog ( @"sortedArrForArrays out of range" );
            
        }

        
    }
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryView=uv;
    
    return cell;
    
}


-(void)action:(UIButton*)sender{
    NSString *cityCode=[self getCityCode:sender.titleLabel.text];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:cityCode forKey:@"cityCode"];
    [defaults setObject:sender.titleLabel.text forKey:@"cityName"];
    
    NSDictionary *dict=@{@"cityCode":cityCode,@"city":sender.titleLabel.text};
    [HTSysParam loadChangeCity:dict];
    [self.delegate cityChanging];
    [self dismissViewControllerAnimated: YES completion: nil ];
}


-(NSString *)getCityCode:(NSString *)city{
    NSString *cityCode=@"";
    for(int i=0;i<[cityArray count];i++){
        NSDictionary *dict=[cityArray objectAtIndex:i];
        NSString *_city=[dict objectForKey:@"city"];
        if([city isEqualToString:_city]){
            cityCode=[dict objectForKey:@"code"];
        }
    }
    
    return cityCode;
}





- (IBAction)closeBarAction:(UIBarButtonItem *)sender {
     [self dismissViewControllerAnimated: YES completion: nil ];
}
@end
